# -*- coding:utf-8 -*-

"""
=============================
this is a feibot product,
all rights reserved.
www.feibot.com
@author: Gu Tianyuan
@email: g@feibot.com
@time: 2023/3/8:10:36
@product: PyCharm
=============================
"""
import socket
import threading
import time
import gtyTools.gtyTypes


class TcpServer:
    def __init__(self, localPort):
        self.localPort = int(localPort)
        self.server = None
        self.rxBuf = ''
        self.txBuf = ''
        self.connectState = False
        self.stopCmd = False
        self.configHandlers = gtyTools.gtyTypes.ConfigHandlers()

    def send(self, data):
        if self.connectState:
            try:
                self.txBuf = data
                return True
            except Exception as e:
                print(e)
                return False
        else:
            return False

    def receive(self):
        if self.connectState:
            try:
                if self.rxBuf != "":
                    return True
            except socket.timeout:  # 如果10秒钟没有接收数据进行提示（打印 "time out"）
                return False
        else:
            return False

    def connect(self):
        try:
            self.stopCmd = False
            self.server = threading.Thread(target=self.start_server)
            self.server.start()
            self.connectState = True
            return True
        except Exception as e:
            self.connectState = False
            print(e)
            return False

    def disconnect(self):
        try:
            self.stopCmd = True
            self.server = None
            self.connectState = False
            return True
        except Exception as e:
            print(e)
            return False

    def reconnect(self):
        try:
            self.disconnect()
            self.connect()
            return True
        except Exception as e:
            print(e)
            return False

    def getState(self):
        return True

    def workerRx(self, client):
        while True:
            # 接收
            data = client.recv(1024)  # 把接收的数据实例化
            self.rxBuf += data.decode(encoding='utf-8')
            if len(data) == 0 or data is None:
                print('disconnected')
                break
            print(data.decode(encoding='utf-8'))
            # 结束
            if self.stopCmd:
                break

    def workerTx(self, client):
        while True:
            # 发送
            if self.txBuf != '':
                client.send(bytes(self.txBuf, encoding='utf-8'))
                self.txBuf = ''
            # 结束
            if self.stopCmd:
                break

    def start_server(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 定义socket类型，网络通信，TCP
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            s.bind(('', self.localPort))  # 套接字绑定的IP与端口
        except OSError as e:
                print(e)
                return
        s.listen(10)  # 开始TCP监听
        while True:
            conn, addr = s.accept()  # 接受TCP连接，并返回新的套接字与IP地址
            print('tcp server connected by client: ', addr)  # 输出客户端的IP地址
            t1 = threading.Thread(target=self.workerRx, args=(conn,))
            t1.start()
            t2 = threading.Thread(target=self.workerTx, args=(conn,))
            t2.start()
            if self.stopCmd:
                break


if __name__ == '__main__':
    s = TcpServer(8801)
    s.connect()
    while True:
        print('aaa')
        s.send('dddssadfafadfda')
        time.sleep(1)
